package com.wu.example;

import static android.provider.BaseColumns._ID;
import static com.wu.example.Constants.TABLE_NAME;
import static com.wu.example.Constants.TIME;
import static com.wu.example.Constants.TITLE;
import static com.wu.example.Constants.CONTENT_URI;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.SimpleCursorAdapter;

public class Events extends ListActivity {

	private static final String TAG = "Events";

	// private EventsData data;

	private static String[] FROM = { _ID, TIME, TITLE };
	private static String ORDER_BY = TIME + " DESC ";

	private static int[] TO = { R.id.rowId, R.id.time, R.id.title };

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.main);

			// data = new EventsData(this);
			addEvents("hello sqlite db");
			Cursor cursor = getEvents();
			showEvents(cursor);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, e.getMessage());
			// data.close();
		}
	}

	private void showEvents(Cursor cursor) {
		// stuff them all into a big string
		// StringBuilder builder = new StringBuilder("save events;\n");
		// while (cursor.moveToNext()) {
		// // could use getColumnIndexOrThrow() to get indexes
		// long id = cursor.getLong(0);
		// long time = cursor.getLong(1);
		// String title = cursor.getString(2);
		// builder.append(id).append(";").append(time).append(":").append(
		// title).append("\n");
		// }
		// // display on the screen
		// TextView text = (TextView) findViewById(R.id.text);
		// text.setText(builder);

		// set up binding
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.item, cursor, FROM, TO);
		setListAdapter(adapter);
	}

	private Cursor getEvents() {
		// perform a managed query , the Activity will handle closing
		// and re-querying the cursor when needed
		// SQLiteDatabase db = data.getReadableDatabase();
		// Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null,
		// ORDER_BY);
		// startManagingCursor(cursor);

		return managedQuery(CONTENT_URI, FROM, null, null, ORDER_BY);
	}

	private void addEvents(String string) {
		// insert a new record into the events data source
		// you would do sometihing similar for delete and update
		// SQLiteDatabase db = data.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(TIME, System.currentTimeMillis());
		values.put(TITLE, string);
		getContentResolver().insert(CONTENT_URI, values);
		// db.insertOrThrow(TABLE_NAME, null, values);
	}
}